import socket, cv, Image
import cv2
import numpy as np
import StringIO

sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.bind(("0.0.0.0", 3220))
print("Waiting for connect...")
sock.listen(2)
client, client_addr = sock.accept()
print("get the connect request from %s", client_addr)
f = client.makefile()
img = np.zeros((640, 480, 3), np.uint8)

while True:
    msg = f.readline()
    if not msg:
        print("Can't get any data")
        break
    jpeg = msg.replace("\-n", "\n")
    buf = StringIO.StringIO(jpeg[0: -1])
    buf.seek(0)
    pi = Image.open(buf)
    img = np.frombuffer(pi.tostring(), dtype=np.uint8)
    img = img.reshape((480, 640, 3))
    # img = cv.CreateImageHeader((640, 480), cv.IPL_DEPTH_8U, 3)
    # cv.SetData(img, pi.tostring())
    buf.close()
    cv2.imshow("show", img)
    if cv2.waitKey(10) == 27:
       break
sock.close()
cv.DestroyAllWindows()
